#! /usr/bin/env python
#
# Implement cookbook using pyfitsio
import sys
import os

import ctypes

from fitsio import cfitsio, pyfitsio

import writeimage
import writeascii
import writebintable
import copyhdu
import selectrows
import readheader
import readimage
import readtable

def unwind_error():
    '''Unwind the stack of errors that may have accumulated'''
    
    errmsg = ctypes.create_string_buffer('\000' * cfitsio.FLEN_ERRMSG)
    count = 0
    while cfitsio.ffgmsg(errmsg):
        print '# ', count, errmsg.value
        count += 1

def main():

    try: 

        writeimage.main()
        writeascii.main()
        writebintable.main()
        copyhdu.main()
        selectrows.main()
        readheader.main()
        readimage.main()
        readtable.main()

        print "\nAll the pyfitsio routines were called successfully"

    except pyfitsio.FitsIOError, e:

        print 'Caught a FitsIOError exception'
        print 'Unwinding error stack'
        unwind_error()
        raise e

    except Exception, e:

        print 'Some other exception occured'
        raise e


if __name__ == '__main__':
    main()
